package cn.hesion;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
/**
 * @author lijing
 * @date 2021/5/11 14:29
 * @description
 */
public class TableDemo {
    public static void main(String[] args) throws Exception {
        //环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //创建tEnv
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        //获取流式数据
        DataStreamSource<Tuple2<String, Integer>> data = env.addSource(new SourceFunction<Tuple2<String, Integer>>() {
            int num = 0;

            @Override
            public void run(SourceContext<Tuple2<String, Integer>> ctx) throws Exception {
                while (true) {
                    ctx.collect(new Tuple2<>("name" + num, num));
                    num++;
                    Thread.sleep(1000);
                }
            }

            @Override
            public void cancel() {

            }
        });
        //将流式数据源作为Table
        Table table = tEnv.fromDataStream(data, $("name"), $("age"));
        //对Table中的数据做查询
        Table name = table.select($("name"));
        DataStream<Tuple2<Boolean, Row>> res = tEnv.toRetractStream(name, Row.class);
        res.print();
        env.execute();
        //定义表数据来源，外部链接
        /*tEnv.connect(new FileSystem().path("D:\\data\\data\\TableTest\\a.txt"))
                .withFormat(new Csv())
                .withSchema(new Schema().field("id", DataTypes.STRING())
                .field("name",DataTypes.STRING()))
                .createTemporaryTable("tmpTable");
        Table result = tEnv.sqlQuery("select * from tmpTable");
        DataStream<Tuple2<Boolean, Row>> res = tEnv.toRetractStream(result, Row.class);
        res.print();*/
//        env.execute();
    }
}